package com.ibuonline.b2b.filter;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.dimeng.common.util.CookieUtil;
import com.dimeng.common.util.EncryptUtil;
import com.dimeng.common.util.StringUtil;
import com.dimeng.common.util.SystemConfig;
import com.ibuonline.b2b.common.ServiceFactory;
import com.ibuonline.b2b.common.SpyMemcached;
import com.ibuonline.b2b.entity.SysUser;
import com.ibuonline.b2b.system.service.SysUserService;

public class AdminCheckLoginFilter implements Filter {

	private Logger logger = Logger.getLogger(AdminCheckLoginFilter.class);
	private SysUserService sysUserService = ServiceFactory.getSysUserService();
	private HashSet<String> ignoreURI;

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) request;

		HttpSession session = httpRequest.getSession();

		if (session.getAttribute("currentAdmin") == null) {
			String uri = httpRequest.getRequestURI();
			if (!uri.endsWith(".do") && !uri.endsWith(".jsp")) {
				filterChain.doFilter(request, response);
				return;
			}
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			CookieUtil util = new CookieUtil(httpRequest, httpResponse);
			String loginName = util.getCookieValue("ln");

			if (StringUtil.notEmpty(loginName)) {
				loginName = EncryptUtil.base64Decode(loginName);
				List<SysUser> sysUsers = sysUserService.getByParam("loginName",	loginName);
				SysUser sysUser = (sysUsers.size() > 0) ? sysUsers.get(0) : null;
				if (sysUser != null) {
					session.setAttribute("currentAdmin", sysUser);
					session.setAttribute("usertype", "admin");
					SpyMemcached.getInstance().set("adminRoles:" + loginName, 
							ServiceFactory.getRoleService().getSysRolesByUserId(sysUser.getUserId()));
					logger.info(sysUser.getLoginName() + " login successful by cookie");
					filterChain.doFilter(request, response);
					return;
				}
			}

			if (!ignoreURI.contains(uri)) {
				System.out.println("This URI can not access without login###########" + uri);
				String message = SystemConfig.getProperty("user.error.not.login");
				httpResponse.sendRedirect(SystemConfig.getAppRoot()+ "admin/login.jsp?message="
						+ URLEncoder.encode(message, "utf-8"));
				return;
			}
		}
		filterChain.doFilter(request, response);

	}

	public void init(FilterConfig arg0) throws ServletException {
		String appRoot = SystemConfig.getAppRoot();
		ignoreURI = new HashSet<String>();
		ignoreURI.add(appRoot + "admin/login.jsp");
		ignoreURI.add(appRoot + "admin/adminLogin.do");
		ignoreURI.add(appRoot + "admin/captcha.do");
		ignoreURI.add(appRoot + "admin/ajaxCheckCode.do");
	}
}
